//
//  NetWorking.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/5/19.
//

import UIKit
import Alamofire
import HandyJSON

class XXNetWorking: NSObject {
    let headers:HTTPHeaders = [
        "Accept": "application/json"
    ]
    
    func get(_ url:String, _ parameters:Dictionary<String, Any>?, suc: @escaping XXDicBlock, fai:@escaping XXStrBlock){
        request(url, method: .get, parameters:parameters, headers: headers).responseJSON { response in
            guard let dic = response.result.value as? [String:Any] else { fai("fail")
                return
            }
            suc(dic)
        }
    }
    
    func post(_ url:String, _ parameters:Dictionary<String, Any>?, suc: @escaping XXDicBlock, fai:@escaping XXStrBlock){
        request(url, method: .post, parameters:parameters, headers: headers).responseJSON { response in
            guard let dic = response.result.value as? [String:Any] else { fai("fail")
                return
            }
            suc(dic)
        }
    }
    
    func get<T: HandyJSON>(_ url:String, _ parameters:Dictionary<String, Any>?, _ model:T.Type, suc:@escaping (_ responseModel: T ) -> () ,fai:@escaping XXStrBlock){
        get(url, parameters, suc: { dic in
            guard let model:T = JSONDeserializer<T>.deserializeFrom(dict: dic) else { return }
            suc(model)
        }, fai: fai)
    }
    
    func post<T: HandyJSON>(_ url:String, _ parameters:Dictionary<String, Any>?, _ model:T.Type, suc:@escaping (_ responseModel: T ) -> () ,fai:@escaping XXStrBlock){
        post(url, parameters, suc: { dic in
            guard let model:T = JSONDeserializer<T>.deserializeFrom(dict: dic) else { return }
            suc(model)
        }, fai: fai)
    }
    
}
